package com.lw.pc;

import javax.swing.plaf.SpinnerUI;

/**
 * @author LW
 * @2020/8/19 11:24
 */
//线程通信问题
    //生产者消费者问题
public class notifyA {

    public static void main(String[] args) {
        Data data = new Data();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.increment();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.decrement();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.increment();
            }
        },"C").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.decrement();
            }
        },"D").start();

    }
}
//判断等待，业务，通知
class Data{
    private int num = 0;

    //+1
    public synchronized void increment(){
        //多线程判断用while不用if   两个线程以上线程就不安全了
        //while 防止虚假唤醒
        while (num!=0){
            //等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        num++;
        System.out.println(Thread.currentThread().getName()+"-->"+num);
        //通知其他线程，+1完毕
        this.notifyAll();//多个线程时，唤醒全部，线程就不安全了
    }

    public synchronized void decrement(){

        while (num==0){
            //等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        num--;
        System.out.println(Thread.currentThread().getName()+"-->"+num);
        //通知其他线程，-1完毕
        this.notifyAll();
    }
}
